package com.tmt.im.common.store;

import com.tmt.im.common.pojo.WalletChangeDetailPoJo;
import lombok.extern.slf4j.Slf4j;

import javax.cache.Cache;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/9/3 16:41
 * @Version 1.0
 **/
@Slf4j
public class WalletChangeDetailStore extends BaseCacheStoreAdapter<Long, WalletChangeDetailPoJo> {

    private static final String SELECT_SQL = StoreSqlHelper.generateSqlWithParams("select", WalletChangeDetailPoJo.class);
    private static final String INSERT_SQL = StoreSqlHelper.generateSqlWithParams("insert", WalletChangeDetailPoJo.class);
    private static final String UPDATE_SQL = StoreSqlHelper.generateSqlWithParams("update", WalletChangeDetailPoJo.class);
    private static final String DELETE_SQL = StoreSqlHelper.generateSqlWithParams("delete", WalletChangeDetailPoJo.class);

    @Override
    public WalletChangeDetailPoJo load(Long key) throws CacheLoaderException {
        try (Connection conn = connection()) {
            try (PreparedStatement st = conn.prepareStatement(SELECT_SQL)) {
                st.setLong(1, key);
                try (ResultSet rs = st.executeQuery()) {
                    if (rs.next()) {
                        WalletChangeDetailPoJo pojo = new WalletChangeDetailPoJo();
                        StoreSqlHelper.initialObject(rs, pojo);
                        return pojo;
                    }
                }
                return null;
            }
        } catch (Exception e) {
            throw new CacheLoaderException("Failed to load: " + key, e);
        }
    }

    @Override
    public void write(Cache.Entry<? extends Long, ? extends WalletChangeDetailPoJo> entry) throws CacheWriterException {
        try {
            Connection conn = connection();
            WalletChangeDetailPoJo val = entry.getValue();
            try (PreparedStatement st = conn.prepareStatement(val.isInsert() ? INSERT_SQL : UPDATE_SQL)) {
                StoreSqlHelper.initPreparedStatement(st, val);
                st.executeUpdate();
            }
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
            throw new CacheWriterException("创建钱包余额变更记录失败：" + e.getMessage(), e);
        }
    }

    @Override
    public void delete(Object key) throws CacheWriterException {
        try {
            Connection conn = connection();
            try (PreparedStatement st = conn.prepareStatement(DELETE_SQL)) {
                st.setLong(1, (Long) key);
                st.executeUpdate();
            }
        } catch (SQLException e) {
            throw new CacheWriterException("Failed to delete: " + key, e);
        }
    }

}
